//
//  HMPictureView.swift
//  WeiBoSwift
//
//  Created by hgj on 2016/11/17.
//  Copyright © 2016年 HuGuoJian. All rights reserved.
//

import UIKit

private let picture_cellId = "picture_cell"

class HMPictureView: UICollectionView {

    var pictureInfos: [HMPictureInfo]? {
        didSet {
            //外界给配图视图设置数据的时候就会执行
            reloadData()
        }
    }
    
    override func awakeFromNib() {
        
        register(UINib(nibName: "HMPictureCell", bundle: nil), forCellWithReuseIdentifier: picture_cellId)
        
        // 代理
        dataSource = self
        delegate = self
    }

}

extension HMPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictureInfos?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: picture_cellId, for: indexPath) as! HMPictureCell
        
        // 可选类型
        cell.pictureInfo = pictureInfos![indexPath.item]
        
        return cell
    }
    
    //实现代理方法
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //显示图片浏览器
        
        /*
         @property (nonatomic, weak) UIView *sourceImagesContainerView;
         @property (nonatomic, assign) NSInteger currentImageIndex;
         @property (nonatomic, assign) NSInteger imageCount;
         
         @property (nonatomic, weak) id<SDPhotoBrowserDelegate> delegate;
         
         - (void)show;
         */
        
        //1. 实例化图片浏览器对象
        let borwser = SDPhotoBrowser()
        //设置容器视图 父视图
        borwser.sourceImagesContainerView = self
        borwser.currentImageIndex = indexPath.item
        borwser.imageCount = pictureInfos?.count ?? 0
        //设置代理
        borwser.delegate = self
        //显示图片浏览器
        borwser.show()
        
    }
}


extension HMPictureView: SDPhotoBrowserDelegate {
    
    //返回高质量图片的url对象
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let picinfo = self.pictureInfos![index]
        let url = URL(string:picinfo.bimiddleImage ?? "")
        return url
    }
    
    //返回一个占位的图片
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        //获取cell
        let indexPath = IndexPath(item: index, section: 0)
        let cell = self.cellForItem(at: indexPath) as? HMPictureCell
        return cell?.imageView.image
        
    }
}



